package com.ruoyi.app.api;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.upload.QiniuUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.CustomId;
import com.ruoyi.system.domain.wx.WxUser;
import com.ruoyi.system.service.wx.IWxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * app端常用非业务接口
 *
 * @author mic
 * @date 2023年9月11日15:23:06
 */
@RestController
@RequestMapping("/wx/common")
public class WxCommon {
    @Autowired
    private IWxUserService userService;

    /**
     * 头像上传
     *
     * @param request
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    public AjaxResult upload(HttpServletRequest request, @RequestParam(value = "file", required = true) MultipartFile file) {
        String userId = (String) request.getAttribute("userId");
        // 先删
        WxUser user = userService.selectWxUserByUserId(userId);
        if (StringUtils.isNotBlank(user.getPic())) {
            QiniuUtils.del(user.getPic());
        }

        if (!file.isEmpty()) {
            // 没有接收到数据
            return AjaxResult.error("没有接收到图片实体!");
        }

        String fileName = file.getOriginalFilename();
        String extName = "." + fileName.substring(fileName.lastIndexOf(".") + 1);
        fileName = "mh/head/" + userId + CustomId.randomWords(4) + extName;

        try {
            boolean upload = QiniuUtils.upload(file.getInputStream(), fileName);
            if (upload) {
                user.setPic(fileName);
                userService.updateWxUser(user);
                return AjaxResult.success("上传成功!", QiniuUtils.DOMAIN + "/" + fileName);
            } else {
                return AjaxResult.error("上传失败!");
            }
        } catch (IOException ioException) {
            System.out.println("头像上传 IO异常!");
            return AjaxResult.error("上传失败!");
        }
    }
}
